package edu.zut.main.ThreadTest;

public class ThreadMoney {
    public static void main(String[] args) {
        Account account = new Account(100);

        DrawAccountMoney boy = new DrawAccountMoney(account,60);
        DrawAccountMoney girl = new DrawAccountMoney(account,30);

        new Thread(boy,"boy").start();
        new Thread(girl,"girl").start();
    }
}
class DrawAccountMoney implements Runnable{
    private Account account;
    private int drawAmount;

    public DrawAccountMoney(Account account, int drawAmount) {
        this.account = account;
        this.drawAmount = drawAmount;
    }

    @Override
    public void run() {
        synchronized (account) {
            if (account.getBalance() >= drawAmount) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.setBalance(account.getBalance() - drawAmount);
                System.out.println(Thread.currentThread().getName() + "取完后,剩下" + account.getBalance());
            } else {
                System.out.println("余额不足！！");
            }
        }
    }
}
class Account{
    private int balance;

    public Account(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }
}
